package com.tanhua.admin.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.db.Log;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 日志消息的监听器
 */
@Component
public class LogListener {

    @Autowired
    private LogMapper logMapper;

    /**
     * 获取到消息 ：String（JSON）
     * 创建对象
     * 保存到数据库
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "tanhua.log.queue"
                    ),
                    exchange = @Exchange(
                            value = "tanhua.log.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "log.*"
            )
    )
    public void log(String message){
        try {
            System.out.println("获取到日志消息="+message);
            //1、解析消息数据
            Map<String,String> map = JSON.parseObject(message, Map.class);
            //2、获取map中的数据
            String logTime = map.get("logTime");
            String type = map.get("type");
            String str = map.get("userId");
            Long userId = Long.valueOf(str);
            //3、创建Log对象
            Log log = new Log(userId,logTime,type);
            //4、保存到数据库中
            logMapper.insert(log);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}
